/**
 * Created by wtfssd on 2017/9/13.
 */
import {AsyncStorage} from 'react-native'
import WebIM from '../components/chat/WebIM';
import {chatService} from '../service/index'
import {Toast} from 'antd-mobile'
import {GiftedChat} from 'react-native-gifted-chat'


import {Actions} from 'react-native-router-flux'

const STORAGE_KEY = "STORAGE_KEY_CHAT";
const homeModel = {
    namespace: 'chat',
    state: {
        isSignIn: false,
        conn: null,
        accessToken: null,
        sendTo: 'server',
        user: 'admin',
        pwd: '123456',
        loading: false,
        messages: [],

    },

    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    }
    ,

    effects: {

        //登陆 并设置监听
        * signIn({payload}, {call, put}) {
            const options = {
                apiUrl: WebIM.config.apiURL,
                ...payload.userInfo,
                appKey: WebIM.config.appkey
            };
            const callBacks = payload.callBacks ? payload.callBacks : {};
            yield put({
                type: 'save',
                payload: {loading: false}
            });
            try {
                const data = yield call(chatService.open, options, callBacks);
                if (data && data.accessToken) {
                    console.log('accessToken', data.accessToken);
                    yield put({
                        type: 'save',
                        payload: {isSignIn: false, accessToken: data.accessToken}
                    });
                    yield put({
                        type: 'saveToStorage',
                        payload: {isSignIn: false, accessToken: data.accessToken, callBacks}
                    })
                } else {
                    Toast.fail('登录失败');
                    yield call(Actions.pop)
                }
                yield put({
                    type: 'save',
                    payload: {loading: false}
                });
            } catch (e) {
                console.log("登录失败", e);
                Toast.fail('登录失败');

                yield call(Actions.pop)
                yield put({
                    type: 'save',
                    payload: {loading: false}
                });
            }
        },

        //登出
        * signOut({payload}, {call, put}) {
            WebIM.conn.close();
            yield put({
                type: 'save',
                payload: {isSignIn: false, accessToken: ''}
            });
            yield put({
                type: 'saveUserToStorage',
                payload: {isSignIn: false, accessToken: ''}
            });
        },


        * sendMsg({payload}, {call, put, select}) {

        },


        //发送消息
        * sendMessage({payload: {message}}, {call, put, select}) {
            console.log('chat', message);
            const {type, data} = message;
            const chat = yield select(state => state.chat);
            let options = {
                apiUrl: WebIM.config.apiURL,
                to: chat.sendTo,
                roomType: false,
                type,
                data,
            };
            let msg = {
                createdAt: message.createdAt,
                sent: true,
                received: false,
                user: {
                    name: chat.user
                }
            };

            try {
                const {id, serverMsgId} = yield call(chatService.sendMessage, options);
                console.log(serverMsgId);
                msg._id = serverMsgId;
                if (type === 'txt') {
                    msg.text = data;
                    const messages = GiftedChat.append(chat.messages, msg);
                    yield put({
                        type: 'save',
                        payload: {messages}
                    })
                }
                if (type === 'img') {
                    msg.image = data.file.data.uri;
                    const messages = GiftedChat.append(chat.messages, msg);
                    yield put({
                        type: 'save',
                        payload: {messages}
                    })
                }
                if (type === 'audio') {
                    msg.audio = data.file.data.uri;
                    const messages = GiftedChat.append(chat.messages, msg);
                    yield put({
                        type: 'save',
                        payload: {messages}
                    })
                }

            } catch (e) {
                console.log('发送失败');
                Toast.fail('发送失败:' + e.message);

            }
        },

        //接受消息
        * onReceivedMessage({payload: {message, callBacks}}, {call, put, select}) {
            const chat = yield select(state => state.chat);
            let msg = {
                createdAt: new Date(),
                _id: message.msg.id,
                sent: false,
                received: true,
                user: {
                    _id: message.msg.from,
                    name: message.msg.from,
                }
            };
            console.log(message);
            if (message.type === 'txt') {
                msg.text = message.msg.data;
                const messages = GiftedChat.append(chat.messages, msg);
                yield put({
                    type: 'save',
                    payload: {messages}
                })
            }
            if (message.type === 'img') {
                msg.image = message.msg.url;
                const messages = GiftedChat.append(chat.messages, msg);
                yield put({
                    type: 'save',
                    payload: {messages}
                })
            }
        },
        //清除聊天记录
        * clean({payload}, {call, put, select}) {
            yield put({
                type: 'save',
                payload: {
                    messages: [], user: 'admin', pwd: '123456', sendTo: 'server'
                }
            });
            yield put({
                type: 'saveToStorage',
                payload: {
                    messages: [], user: 'admin', pwd: '123456', sendTo: 'server'
                }
            });
        },

        //保存用户信息到本地存储
        * saveToStorage({payload}, {call}) {
            console.log('saveToStorage', payload);
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        //从本地存储中恢复用户信息
        * restoreFromStorage({payload}, {call, put}) {
            let jsonString = yield call(AsyncStorage.getItem, STORAGE_KEY);
            let jsonObj = JSON.parse(jsonString);
            yield put({
                type: 'save',
                payload: {...jsonObj}
            })
        },
    },

    subscriptions: {
        setup({dispatch}) {
            //启动时从本地存储中恢复用户信息
            dispatch({
                type: 'restoreFromStorage',
            })
        }
    },
};

export default homeModel